package sy.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sy.model.Taskrecord;
import sy.model.Tinviterecord;
import sy.model.Tuser;
import sy.pageModel.Mshake;
import sy.pageModel.Mtaskrecord;
import sy.pageModel.SessionInfo;
import sy.pageModel.User;
import sy.service.InviteServiceI;
import sy.service.ShakeServiceI;
import sy.service.TaskRecordServiceI;
import sy.service.UserServiceI;
import sy.util.ConfigUtil;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户控制器
 * 
 * @author 孙宇
 * 
 */
@Controller
@RequestMapping("/tshakeController")
public class TshakeController extends BaseController {
	@Autowired
	private ShakeServiceI shakeService;
	
	@Autowired
	private UserServiceI userService;
	
	@Autowired
	private TaskRecordServiceI taskrecordService;
	
	@Autowired
	private UserController usercontrol;
    @Autowired
    private InviteServiceI inviteService;

	/**
	 * 每日一摇
	 * 
	 * @param id
	 * 
	 */
	@ResponseBody
	@RequestMapping("/addshake")
	public String addshakerecord(Mshake shake, HttpSession session) {
		JSONObject jsobj = new JSONObject();
		try {
			SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());
			if(sessionInfo == null){
				jsobj.put("status", -1);
				jsobj.put("msg", "登录超时");
			}else{
			Date currentTime = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		    Date dateString =formatter.parse(formatter.format(currentTime));
			int count = taskrecordService.getexistshake(sessionInfo.getUserid(), dateString);													//查询用户是否当天签到
		    int pub=0;
				if(count==0){
				Mtaskrecord  task = new Mtaskrecord();
				task.setTaskType("4");							//设置类型
				task.setUserid(sessionInfo.getUserid());		//设置用户id
				int a[] = new int[1];
			    a[0] = (int) (Math.random() * 10); 
		        if(a[0] == 0){		  //表示一等奖
                    pub=20000;

		        }else if(a[0] == 1 ){  //表示二等奖
		        	pub=10000;//task.setScore(10000);
		        }else if(a[0] == 3 || a[0] == 2){  //表示三等奖
		        	pub=5000;//task.setScore(5000);
		        }else if(a[0] == 9)	{
		        	pub=500;//task.setScore(500);
		        }else{
                    pub=2000;//task.setScore(2000);
		        }
                task.setScore(pub);
				taskrecordService.add(task);//设置积分
				jsobj.put("status", 1);
				jsobj.put("msg", task.getScore());
				usercontrol.updatetotalscore(sessionInfo.getId(),task.getScore(), 1);
                //三级分成

                getMoenyTo(pub,sessionInfo);


			}else{
				jsobj.put("status", 0);
				jsobj.put("msg", "你今天摇咯!");
			}
		 }
		} catch (Exception e) {
			e.printStackTrace();
			jsobj.put("status", 0);
			jsobj.put("msg", "系统错误");
		}
		return jsobj.toJSONString();
	}
    //userid:邀请人id inviteuserid：被邀请人id 获得被邀请人的所有父级邀请人id 向上面找三级
    public List<Tinviterecord> getTGClass(String userid)throws Exception{

        List<Tinviterecord> tinviterecords=new ArrayList<Tinviterecord>();

        Tinviterecord tinviterecord1=null;
        Tinviterecord tinviterecord2=null;
        Tinviterecord tinviterecord3=null;
        //如果不为空表示存在上级推广  第一级
        tinviterecord1=inviteService.getUpClass(userid);

        if(tinviterecord1!=null){
            tinviterecords.add(tinviterecord1);
            //找第二级
            tinviterecord2= inviteService.getUpClass(tinviterecord1.getUserid());
            if(tinviterecord2!=null){
                tinviterecords.add(tinviterecord2);
                //找第三级
                tinviterecord3= inviteService.getUpClass(tinviterecord2.getUserid());
                if(tinviterecord3!=null){
                    tinviterecords.add(tinviterecord3);
                }
            }

        }

        return tinviterecords;
    }
    //三级分成
    public void getMoenyTo(Integer pub,SessionInfo sessionInfo){
        try{
            //定义三级推广用户所加积分变量
            long gold1=0;

            Tinviterecord tinviterecord=inviteService.getUpClass(sessionInfo.getUserid()+"");
            if(tinviterecord!=null){//改用户是被邀请  第一次做人要 7W
                //判断是否第一次做任务
                List<Taskrecord> taskrecords= taskrecordService.gettask(sessionInfo.getUserid());
                if(taskrecords.size()<=0){//第一次做任务
                    gold1+=70000;

                }
                //获得这个用户推广向上三级 用户
                List<Tinviterecord> tinviterecords= getTGClass(sessionInfo.getUserid()+"");
                long gold=0;
                for(int i=0;i<tinviterecords.size();i++){
                    Tuser u = null;
                    User user = new User();
                    if(i==0){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.35;
                        gold= (long)t+gold1;//加上第一次做任务积分 没有加0

                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)gold);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)gold);
                        userService.editotlescore(user);

                        //     usercontrol.updatetotalscore(u.getId(),(int)gold , 1);//更新积分

                    }else if(i==1){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.1;

                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)t);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)t);
                        userService.editotlescore(user);

                    }else if(i==2){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.05;
                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)t);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)t);
                        userService.editotlescore(user);

                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
	 * 摇杆机
	 * 
	 * @param id
	 * 
	 */
	@ResponseBody
	@RequestMapping("/addRockercopy")
	public String addrockrecord(Mshake shake, HttpSession session) {
		JSONObject jsobj = new JSONObject();
		try {
			SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());
			if(sessionInfo == null){
				jsobj.put("status", -1);
				jsobj.put("msg", "登录超时");
			}else{
			User user  = userService.get(sessionInfo.getId());
			Date currentTime = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		    Date dateString =formatter.parse(formatter.format(currentTime));
			int  count = taskrecordService.getexistrock(user.getUserid(), dateString);
            int pub=0;
			if(count <=400){
			if(user.getTotalscore()>shake.getScore()){				//表示下注积分
				if(user.getLevl()<5){								//判断级别数据是否够
					Mtaskrecord  task = new Mtaskrecord();			//增加积分
					int a[] = new int[1];
				    a[0] = (int) (Math.random() * 10); 
			        if(a[0] == 0){		  				 //表示一等奖
                        pub=shake.getScore()*4;

			        }else if(a[0] == 1 || a[0] == 2){    //表示二等奖
			        	pub=shake.getScore()*2 ;//task.setScore(shake.getScore()*2);
			        }else{ 								 //表示三等奖
			        	pub=0;//task.setScore(0);
			        }
                    task.setScore(pub);
					task.setTaskType("5");							//设置类型
					task.setUserid(sessionInfo.getUserid());		//设置用户id
					task.setScore(10000);							//设置积分
					taskrecordService.add(task);
					usercontrol.updatetotalscore(sessionInfo.getId(), task.getScore(), 4);
					
					Mtaskrecord  tasklost = new Mtaskrecord();
					tasklost.setTaskType("5");						//设置类型
					tasklost.setUserid(sessionInfo.getUserid());	//设置用户id
					tasklost.setScore(0-shake.getScore());			//设置积分--存放负数
					taskrecordService.add(tasklost);
					usercontrol.updatetotalscore(sessionInfo.getId(), shake.getScore(), 2);

                    //三级分成

                    getMoenyTo(pub,sessionInfo);


					jsobj.put("status", 1);
					jsobj.put("msg",  task.getScore());
				}else{
					jsobj.put("status", 0);
					jsobj.put("msg", "您的级数还不够");
				}
			}else{													//表示积分不够
					jsobj.put("status", 0);
					jsobj.put("msg", "您当前的积分不够下注");
			}
		  }else{
			  		jsobj.put("status", 0);
			  		jsobj.put("msg", "每天不能超过两百次噢");
		  }
		 }
		} catch (Exception e) {
			e.printStackTrace();
			jsobj.put("status", 0);
			jsobj.put("msg","系统错误");
		}
		return jsobj.toJSONString();
	}
	

	/**
	 * 摇杆机改版
	 * 
	 * @param id
	 * 
	 */
	@ResponseBody
	@RequestMapping("/addRocker")
	public String rocdact(Integer lostscore,Integer  score, HttpSession session,HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		JSONObject jsobj = new JSONObject();
			try {
				SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
				if(sessionInfo == null){
					jsobj.put("status", -1);
					jsobj.put("msg", "登录超时");
				}else{
				User user = userService.get(sessionInfo.getId());
				Date currentTime = new Date();
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				Date dateString = formatter.parse(formatter.format(currentTime));
				int count = taskrecordService.getexistrock(user.getUserid(),dateString);
				if(count < 11){
					if(user.getTotalscore()>lostscore){						//表示下注积分
						if(user.getLevl()>5){								//判断级别数据是否够
							Mtaskrecord  task = new Mtaskrecord();			//加分计划
							task.setTaskType("5");							//设置类型
							task.setUserid(sessionInfo.getUserid());		//设置用户id
							task.setScore(score);							//设置积分
							taskrecordService.add(task);
							usercontrol.updatetotalscore(sessionInfo.getId(), score, 1);
							Mtaskrecord  tasklost = new Mtaskrecord();		//减分
							tasklost.setTaskType("5");						//设置类型
							tasklost.setUserid(sessionInfo.getUserid());	//设置用户id
							tasklost.setScore(0-lostscore);					//设置积分--存放负数
							taskrecordService.add(tasklost);
							usercontrol.updatetotalscore(sessionInfo.getId(), lostscore, 4);
							jsobj.put("status", 1);
							jsobj.put("msg", score);
						}else{
							jsobj.put("status", 0);
							jsobj.put("msg", "您的级数还不够");
						}
					}else{													//表示积分不够
							jsobj.put("status", 0);
							jsobj.put("msg", "您当前的积分不够下注");
					}
				  }else{
					  		jsobj.put("status", 0);
					  		jsobj.put("msg", "每天不能超过两百次噢");
				  }
				}
			} catch (Exception e) {
				e.printStackTrace();
				jsobj.put("status", 0);
		  		jsobj.put("msg", "系统错误");
			}
		 return jsobj.toJSONString();
	}
}
